import axios from 'axios'
import { removeItem, getItem } from '@/utils/auth.js'
import router from '@/router/index.js'
// 引入组件,message===this.$message
import { Message } from 'element-ui'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})
_axios.interceptors.request.use(
  config => {
    // headers: {
    //   Authorization: `Bearer ${getItem()}`
    // }
    // 通过请求拦截设置token值
    config.headers.Authorization = `Bearer ${getItem()}`
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
_axios.interceptors.response.use(
  res => {
    return res.data
  },
  error => {
    // 创建统一的报错提醒
    if (error.response.data && error.response.data.message) {
      Message.error(error.response.data.message)
    }
    if (error.response.status === 401) {
      removeItem()
      router.push('/login')
    }
    return Promise.reject(error)
  }
)
export default _axios
